package cate.game.server.rpc.fax;

import cate.game.server.rpc.FaxClientHandler;
import cp.game.framework.ConfigFromConsole;
import cp.solution.business.cloud.CloudFaxEntity;
import cp.solution.define.GameFeature;
import cp.solution.define.SrvType;
import cp.solution.fax.FaxTags;
import easy.java.io.http.LocationSearch;
import fax.client.FaxClient;
import fax.client.FaxClientBuilder;
import fax.client.util.FaxClientHollow;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FaxGameUtils {

    public static FaxClient buildFaxClient(ConfigFromConsole configFromConsole, FaxClientHandler faxClientHandler) throws Exception {
        CloudFaxEntity fax = configFromConsole.progressBootstrap.getFax();
        if (fax == null) {
            log.warn("build a hollow fax client");
            return new FaxClientHollow();
        }
        boolean ac = false;
        try {
            LocationSearch fs = configFromConsole.progressBootstrap.getProcess().toFeatureSearch();
            ac = fs.getBoolean(GameFeature.FAX_CONCURRENCY, false);
            log.info("fax并发启用 = {}", ac);
        } catch (Exception e) {
            log.error("", e);
        }
        FaxClientBuilder builder = FaxClientBuilder.create().uid(configFromConsole.processCode)
                .nodeHost(fax.getHost()).nodePort(fax.getPort())
                .clientHandler(faxClientHandler).reconnectInterval(10_000)
                .autoConcurrency(ac);
        builder.addTag(FaxTags.TAG_SRV_TYPE, SrvType.game.name())
                .addTag(FaxTags.TAG_GAME_PROCESS_CODE, configFromConsole.processCode);
        for (int srvId : configFromConsole.srvIds) {
            builder.addTag(FaxTags.TAG_GAME_SRV_ID, srvId);
        }
        for (String crossCode : configFromConsole.crossCodeList) {
            builder.addTag(FaxTags.TAG_CROSS_CODE, crossCode);
        }
        for (String groupCode : configFromConsole.groupCodeList) {
            builder.addTag(FaxTags.TAG_GROUP_CODE, groupCode);
        }
        FaxClient fc = builder.build();
        try {
            fc.connect();
        } catch (Exception e) {
            log.error("fax connect fail, because {}, maybe haven't deploy fax-node({}:{}).", e.getMessage(), fax.getHost(), fax.getPort());
        }
        return fc;
    }
}
